<template>
  <div class="table-header">
    <el-input placeholder="Please input" v-model="inputVal" @keyup.enter="search">
      <template #append>
        <el-button :icon="SearchOutlined" @click="search" />
      </template>
    </el-input>
    <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
  </div>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column type="index" label="#" width="50" />
    <el-table-column prop="username" label="姓名" />
    <el-table-column prop="email" label="邮箱" />
    <el-table-column prop="mobile" label="电话" />
    <el-table-column prop="mg_state" label="状态">
      <template #default="scope">
        <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
      </template>
    </el-table-column>

    <el-table-column label="操作" width="180">
      <template #default="scope">
        <el-button type="primary" size="small" :icon="EditOutlined" @click="editUser(scope.row)"></el-button>

        <el-popconfirm width="220" confirm-button-text="是的" cancel-button-text="不, 谢谢" :icon="InfoFilled"
          icon-color="#626AEF" title="你确定要删除这条数据吗?" @onConfirm="deleteuser(scope.row)" @confirm="deleteuser(scope.row)">
          <template #reference>
            <el-button type="danger" size="small" :icon="DeleteOutlined"></el-button>
          </template>
        </el-popconfirm>

        <el-tooltip content="分配角色" effect="light" placement="right" :enterable="false">
          <el-button type="warning" size="small" :icon="SettingOutlined" @click="assignRoles(scope.row)"></el-button>
        </el-tooltip>
      </template>
    </el-table-column>


  </el-table>
  <!--分页-->
  <!-- <el-config-provide :locale="zhCn"/> -->
  <el-pagination v-model:currentPage="currentPage" v-model:pageSize="pageSize" :page-sizes="[1, 2, 3, 4]" :small="small"
    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />
  <!-- 如果当前页不是第一页切换每页显示的数量，将会导致 handleSizeChange和handleCurrentChange都被调用 -->
  <!-- <el-form ref:用于获取表单元素>model是表单数据对象，rules是表单验证规则。</el-form> -->
  <!-- 添加用户对话框 -->
  <el-dialog v-model="dialogFormVisible" title="添加用户">
    <el-form :model="form" :rules="rules" ref="ruleFormRef">
      <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
        <el-input v-model="form.password" autocomplete="off" type="password" />
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
        <el-input v-model="form.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号" :label-width="formLabelWidth" prop="mobile">
        <el-input v-model="form.mobile" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
        <el-button @click="resetForm(ruleFormRef)">
          重置
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- users post方法 改接口用于添加用户直接调用即可添加用户 -->


  <!-- 编辑用户对话框 -->
  <el-dialog v-model="editdialogFormVisible" title="编辑用户">
    <el-form :model="editform" :rules="rules2" ref="ruleEditFormRef">
      <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
        <el-input v-model="editform.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
        <el-input v-model="editform.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号" :label-width="formLabelWidth" prop="mobile">
        <el-input v-model="editform.mobile" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitEditForm(ruleEditFormRef)">提交</el-button>
        <el-button @click="resetEditForm(ruleEditFormRef)">
          重置
        </el-button>
      </span>
    </template>
  </el-dialog>


  <!-- 分配角色对话框 -->
  <el-dialog v-model="dialogRoleVisible" title="分配角色" width="30%">
    <div>
      <p>当前的用户：{{ currentUser.username }}</p>
      <p>当前的角色：{{ currentUser.role_name }}</p>
      <p>分配的角色：
        <el-select v-model="selectedRoleId" placeholder="请选择" size="large" :teleported="false">
          <el-option v-for="item, index in roleList" :key="index" :label="item.roleName" :value="item.id" />
        </el-select>

      </p>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取消</el-button>
        <el-button type="primary" @click="setRole">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
  <!-- formEL.validate((valid)=>{
    if(valid){
        //验证通过的代码
    }else{
        //验证不通过的代码
    }
}) -->


<script setup>
import { DeleteOutlined, EditOutlined, SearchOutlined, SettingOutlined } from '@ant-design/icons-vue';
import { InfoFilled } from '@element-plus/icons-vue'
import axios from '../../axios.js';
import { ref, onBeforeMount, watchEffect, reactive } from 'vue'
import { ElMessage } from 'element-plus';

const tableData = ref([]);
const inputVal = ref('')
const total = ref(1)
const currentPage = ref(1)
const pageSize = ref(3)
const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = '140px';
const form = reactive({
  username: '',
  password: '',
  email: '',
  mobile: ''
})


let netData = ref([])

const getuser = async () => {
  const { data: res } = await axios.get(`users?pagenum=${currentPage.value}&pagesize=${pageSize.value}`)
  tableData.value = [];
  res.data.users.forEach(ele => {
    tableData.value.push({
      id: ele.id,
      username: ele.username,
      email: ele.email,
      mobile: ele.mobile,
      mg_state: ele.mg_state,
      role_name: ele.role_name
    })
  })
  total.value = res.data.total;
  netData.value = tableData.value
}

const search = () => tableData.value = netData.value.filter(val => val.username.indexOf(inputVal.value) != -1)

onBeforeMount(() => {
  getuser();
})
watchEffect((currentPage, pageSize) => {
  getuser()
})

const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize.value = val
}
const handleCurrentChange = (val) => { console.log(`current page:${val}`); currentPage.value = val }


const ruleFormRef = ref(null)
const rules = reactive({
  username: [{
    required: true, message: '请输入用户名', trigger: 'blur'
  }, {
    min: 5, max: 10, message: '用户名长度在 5 到 10', trigger: 'blur'
  }],
  password: [{
    required: true, message: '请输入密码', trigger: 'blur'
  }, {
    min: 6, max: 12, message: '用户名长度在 6 到 12', trigger: 'blur'
  }],
  email: [{
    type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'
  }], mobile: [{
    message: '请输入正确的手机号', pattern: "^1(3[0-9]|5[012356789]|7[1235678]|8[0-9])\\d{8}$", trigger: 'blur'
  }]
})

const submitForm = async (formEL) => {
  if (!formEL) return
  await formEL.validate(async (valid, fields) => {
    if (valid) {
      const { data: res } = await axios.post('/users', {
        username: form.username, password: form.password, email: form.email, mobile: form.mobile
      })
      getuser()
      dialogFormVisible.value = false
    } else {
      console.log('error submit!', fields);
    }
  })
}

const resetForm = (formEL) => {
  if (!formEL) return
  formEL.resetFields()
}
const changeState = async (user) => {
  const { data: res } = await axios.put(`users/${user.id}/state/${user.mg_state}`)
}


const rules2 = reactive({
  username: [{
    required: true, message: '请输入用户名', trigger: 'blur'
  }, {
    min: 5, max: 10, message: '用户名长度在 5 到 10', trigger: 'blur'
  }],
  email: [{
    type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'
  }],
  mobile: [{
    message: '请输入正确的手机号', pattern: "^1(3[0-9]|5[012356789]|7[1235678]|8[0-9])\\d{8}$", trigger: 'blur'
  }]
})
const ruleEditFormRef = ref(null)
const editdialogFormVisible = ref(false);
const editform = reactive({
  username: '',
  email: '',
  mobile: ''
})
const editUser = (user) => {
  editdialogFormVisible.value = true;
  editform.id = user.id;
  editform.username = user.username;
  editform.email = user.email;
  editform.mobile = user.mobile;
}
const submitEditForm = async (formEL) => {
  if (!formEL) return
  await formEL.validate(async (valid, fields) => {
    if (valid) {
      const { data: res } = await axios.put(`/users/${editform.id}`, { username: editform.username, email: editform.email, mobile: editform.mobile })
      getuser()
      editdialogFormVisible.value = false
    } else {
      console.log('error submit!', fields);
    }
  })
}

const resetEditForm = (formEL) => {
  if (!formEL) return
  formEL.resetFields()
}

const deleteuser = async (user) => {
  const { data: res } = await axios.delete(`/users/${user.id}`);
  getuser();
}

const dialogRoleVisible = ref(false);
const currentUser = ref(null);
const roleList = ref([])
const selectedRoleId = ref(undefined)
const assignRoles = async (user) => {
  dialogRoleVisible.value = true;
  currentUser.value = user;
  roleList.value = [];
  const { data: res } = await axios.get(`roles`);
  roleList.value = res.data;
}

const setRole = async () => {
  dialogRoleVisible.value = false;
  const { data: res } = await axios.put(`users/${currentUser.value.id}/role`, { rid: selectedRoleId.value })
  if (res.meta.status != 200) return ElMessage.error('分配角色失败');
  getuser();
  ElMessage.success('分配角色成功');
}

const resetDialogRole = () => {
  currentUser.value = {};
  selectedRoleId.value = undefined;
}

</script>
<style scoped> .table-header {
   margin-bottom: 20px;
 }

 .table-header .el-input {
   width: 300px;
   margin-right: 20px;
 }

 .el-pagination {
   margin-top: 30px;
 }

 .el-button--text {
   margin-right: 15px;
 }

 .el-select {
   width: 300px;
 }

 .el-input {
   width: 300px;
 }

 .dialog-footer button:first-child {
   margin-right: 10px;
 }
</style>